package com.ymm.web.controller;

import com.ymm.driver.api.constants.Dto.DriverDto;
import com.ymm.driver.api.constants.Dto.DriverGrabDto;
import com.ymm.driver.api.constants.Entity.DrbillEntity;
import com.ymm.driver.api.constants.Entity.DriverEntity;
import com.ymm.driver.api.facade.CreateRandomNumService;
import com.ymm.driver.api.facade.DriverPersonalAllInformationService;
import com.ymm.driver.api.utils.DateUtils;
import com.ymm.driver.api.utils.MD5Utils;
import com.ymm.driver.api.utils.PhoneCheckUtils;
import com.ymm.driver.api.utils.Result;
import com.ymm.system.api.dto.CargoDTO;
import com.ymm.system.api.dto.CargoInfoDto;
import com.ymm.system.api.dto.DriverGrabDTO;
import com.ymm.system.api.dto.TradeShowDTO;
import com.ymm.system.api.facade.SystemDisplayService;
import com.ymm.system.api.facade.SystemDriverOrderTradeService;
import com.ymm.system.api.facade.SystemGenerateOrderTradeService;
import com.ymm.system.api.facade.SystemMatchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.BigInteger;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * @Company: CUG
 * @Description: TODO
 * @Author: LiYangyong
 * @Date: 2022/8/1/001 23:07
 **/


@Slf4j
@RestController
@RequestMapping("/driver")
public class DriverController {


    /**
     * 测试用例
     */
    /*@Reference
    DemoDubboService demoDubboService;

    @Reference
    DriverDemoService driverDemoService;



    @RequestMapping("/getMsg")
    public String getMsg(String str) {

        log.info("str:{}", str);
        String s = demoDubboService.showMsg(str);
        return s;
    }


    @RequestMapping("/test")
    public String getName(@PathVariable() BigInteger driverId) {
        log.info("driverId:{}", driverId);
        String driverName = driverDemoService.selectInformationByDriverId(driverId);
        return driverName;
    }
*/





    @Reference(version = "server")
    DriverPersonalAllInformationService driverPersonalAllInformationService;

    /*@Reference(version = "server")
    DriverFindAllOrdersService driverFindAllOrdersService;*/

    @Reference(version = "server")
    SystemMatchService systemMatchService;

    @Reference(version = "server")
    SystemDriverOrderTradeService systemDriverOrderTradeService;

    @Reference(version = "server")
    SystemGenerateOrderTradeService systemGenerateOrderTradeService;

    @Reference(version = "server")
    SystemDisplayService systemDisplayService;


    @Autowired
    private ThreadPoolTaskExecutor executor;


    /**
     * 抢派单逻辑  立即抢单
     *
     * @return
     */
    @PostMapping("/grabCargo")
    public Result grabCargo(DriverGrabDTO driverGrabDTO) {
        com.ymm.system.api.utils.Result result = systemGenerateOrderTradeService.generateOrder(driverGrabDTO);
        System.out.println(result);
        if (result.getCode() == 201) {
            return Result.fail("货源不存在");
        }

        return Result.success("抢单成功");

    }


    /**
     * 更改运单状态
     *
     * @param tradeId
     * @return
     */
    @RequestMapping("/updateTradeState")
    public Result updateTradeState(Long tradeId) {
        systemDriverOrderTradeService.updateTradeState(tradeId);
        return Result.success("更改状态成功！");
    }

    /**
     * 获取订单详情
     *
     * @param driverId
     * @param
     * @return
     */
    @RequestMapping("/getOrder")
    public Result getOrder(Long driverId, Long orderId) {
        TradeShowDTO tradeInfo = systemDriverOrderTradeService.getTradeInfo(driverId, orderId);
        return Result.success(tradeInfo);
    }


    /**
     * 获取运单列表
     *
     * @return
     */
    @RequestMapping("/getOrdersList")
    public com.ymm.system.api.utils.Result getTradeListTest(Long driverId) {
        // 司机拿运单列表
        return systemDriverOrderTradeService.getTradeLists(driverId);

    }


    @RequestMapping("/getOrderProcessList")
    public com.ymm.system.api.utils.Result getTradeProcessListTest(Long driverId) {
        // 司机拿进行中运单列表
        return systemDriverOrderTradeService.getTradeProgressLists(driverId);
    }

    @RequestMapping("/getOrderHistoryList")
    public com.ymm.system.api.utils.Result getTradeHistoryListTest(Long driverId) {
        // 司机拿历史运单列表
        return systemDriverOrderTradeService.getTradeHistoryLists(driverId);
    }

    /**
     * 根据司机ID查询司机信息
     *
     * @param driverId
     * @return
     */
    @RequestMapping("/searchDriverInfo")
    private Result test(BigInteger driverId) {
        log.info("driverId:{}", driverId);
        Result result = driverPersonalAllInformationService.driverSearchInfo(driverId);


        return result;
    }


    /**
     * 查询司机流水，调用异步线程
     *
     * @param driverId
     * @return
     */
    @RequestMapping("/showDrbill")
    public Result showDrbill(BigInteger driverId) {
        List<DrbillEntity> drbillEntities = driverPersonalAllInformationService.showDrbill(driverId);
        return Result.success(drbillEntities);
    }


    /**
     * 调用洪源的接口，放到第三个list里
     * 备注：
     *      系统洪源的service jia包
     */


    /**
     * 司机点击当天货源，从系统获取货源信息
     * 测试条件
     * 带有经、纬度、车型的货源信息表，和司机经、纬度
     *
     * @param driverLat     司机经度
     * @param driverLon     司机纬度
     * @param driverCarType 司机车型
     * @return
     */
    @RequestMapping("/findDayCargo")
    public Result findCargo(BigInteger driverId, Double driverLat, Double driverLon, Integer driverCarType, Integer cargoSortNum) throws ExecutionException, InterruptedException {

        // 如果没认证车辆信息，返回空
        if (driverCarType == null || driverPersonalAllInformationService.driverSearchInfo(driverId).getData().getDriverCarType() == null) {
            return Result.fail("请认证车辆信息！");
        }


        // 1. 判断司机是否是会员
        int driverType = driverPersonalAllInformationService.selectDriverTypeByDriverId(driverId);



        // 2. 从系统拿到所有的货源信息
        com.ymm.system.api.utils.Result<List<CargoDTO>> allCargo = systemMatchService.driverSearchDayCargoService(driverLat, driverLon, driverCarType);



        // 3. 根据司机是否是会员判断返回货源列表
        // 直接把司机会员状态给前端，前端根据这个判断能不能抢


        // 4.无论是不是会员都根据货源时间派判断司机可以抢的单
        List<List<CargoDTO>> twoCargoList = new ArrayList<>();
        List<CargoDTO> driverCanGrabCargoList = new ArrayList<>();
        List<CargoDTO> driverCanNotGrabCargoList = new ArrayList<>();
        // 当前时间
        Date nowTime = new Date();

        if (allCargo.getData() == null) {
            return Result.fail("当前没有货源！");
        }


        // 5. 根据时间判断司机可以抢的货源
        for (int i = 0; i < allCargo.getData().size(); i++) {
            // 获取货源创建时间
            Date cargoCreateTime = allCargo.getData().get(i).getCargoCreateTime();


            long nowTimeSec = nowTime.getTime();
            long cargoTim = cargoCreateTime.getTime();

            // 时间差
            long temp = nowTimeSec - cargoTim;
            long nm = 1000 * 60;
            // 货源发出的总分钟
            long totalTime = temp / nm;

            if (totalTime <= 5) {
                driverCanNotGrabCargoList.add(allCargo.getData().get(i));
            } else {
                driverCanGrabCargoList.add(allCargo.getData().get(i));
            }
        }


        // 系统那边的货源筛选
        com.ymm.system.api.utils.Result<List<CargoDTO>> listResult = systemMatchService.PushLongTimeCargo(driverLat, driverLon, driverCarType, driverId.longValue());



        // 未排序
        /*twoCargoList.add(driverCanNotGrabCargoList);
        twoCargoList.add(driverCanGrabCargoList);
        twoCargoList.add(listResult.getData());*/

        if (cargoSortNum != null && cargoSortNum == 1) { // cargoSortNum = 1 时进行价格排序


            // 起始时间
            long start = System.currentTimeMillis();

            Callable<List<CargoDTO>>  driverCanGrabCargoSortListCall = new Callable<List<CargoDTO>>() {
                @Override
                public List<CargoDTO> call() throws Exception {

                    // 都可抢价格从低到高排序
//                    Map<Integer, CargoDTO> driverCanGrabCargoMap = new HashMap<>();
//                    List cargoPriceList = new ArrayList();
//                    if (driverCanGrabCargoList.size() != 0) {
//                        for (int i = 0; i < driverCanGrabCargoList.size(); i++) {
//                            cargoPriceList.add(driverCanGrabCargoList.get(i).getCargoPrice());
//                            driverCanGrabCargoMap.put(driverCanGrabCargoList.get(i).getCargoPrice(), driverCanGrabCargoList.get(i));
//                        }
//                        Collections.sort(cargoPriceList);
//                    }
//                    List driverCanGrabCargoSortList = new ArrayList();
//                    for (int i = driverCanGrabCargoList.size() - 1; i >= 0; i--) {
//                        driverCanGrabCargoSortList.add(driverCanGrabCargoMap.get(cargoPriceList.get(i)));
//                    }
                    List<CargoDTO> driverCanGrabCargoSortList = new ArrayList();
                    for (CargoDTO cargoDTO : driverCanGrabCargoList) {

                        driverCanGrabCargoSortList.add(cargoDTO);
                    }
//                    driverCanGrabCargoSortList.sort(Comparator.comparing(CargoDTO::getCargoPrice));
                    driverCanGrabCargoSortList.sort((a, b) -> b.getCargoPrice().compareTo(a.getCargoPrice()));

                    return driverCanGrabCargoSortList;
                }
            };
            Future<List<CargoDTO>> driverCanGrabCargoSortListFuture = executor.submit(driverCanGrabCargoSortListCall);



            Callable<List<CargoDTO>> driverCanNotGrabCargoSortListCall = new Callable<List<CargoDTO>>() {
                @Override
                public List<CargoDTO> call() throws Exception {
                    // 不可抢价格从高到底排序
//                    Map<Integer, CargoDTO> driverCanNotGrabCargoMap = new HashMap<>();
//                    List cargoPriceNotList = new ArrayList();
//                    if (driverCanNotGrabCargoList.size() != 0) {
//                        for (int i = 0; i < driverCanNotGrabCargoList.size(); i++) {
//                            cargoPriceNotList.add(driverCanNotGrabCargoList.get(i).getCargoPrice());
//                            driverCanNotGrabCargoMap.put(driverCanNotGrabCargoList.get(i).getCargoPrice(), driverCanNotGrabCargoList.get(i));
//                        }
//                        Collections.sort(cargoPriceNotList);
//                    }
//                    List driverCanNotGrabCargoSortList = new ArrayList();
//                    for (int i = driverCanNotGrabCargoList.size() - 1; i >= 0; i--) {
//                        driverCanNotGrabCargoSortList.add(driverCanNotGrabCargoMap.get(cargoPriceNotList.get(i)));
//                    }
                    List<CargoDTO>  driverCanNotGrabCargoSortList = new ArrayList();
                    for (CargoDTO cargoDTO : driverCanNotGrabCargoList) {

                        driverCanNotGrabCargoSortList.add(cargoDTO);
                    }
//                    driverCanNotGrabCargoSortList.sort(Comparator.comparing(CargoDTO::getCargoPrice));
                    driverCanNotGrabCargoSortList.sort((a, b) -> b.getCargoPrice().compareTo(a.getCargoPrice()));
                    return driverCanNotGrabCargoSortList;
                }
            };
            Future<List<CargoDTO>> driverCanNotGrabCargoSortListFuture = executor.submit(driverCanNotGrabCargoSortListCall);



            Callable<List<CargoDTO>> driverSystemCargoSortListCall = new Callable<List<CargoDTO>>() {
                @Override
                public List<CargoDTO> call() throws Exception {
                    // 系统那边30分钟的价格排序
//                    Map<Integer, CargoDTO> driverSystemCargoMap = new HashMap<>();
//                    List driverSystemCargoList = new ArrayList();
//                    List driverSystemCargoSortList = new ArrayList();
//                    if (listResult.getData() != null && listResult.getData().size() != 0) {
//                        for (int i = 0; i < listResult.getData().size(); i++) {
//                            driverSystemCargoList.add(listResult.getData().get(i).getCargoPrice());
//                            driverSystemCargoMap.put(listResult.getData().get(i).getCargoPrice(), listResult.getData().get(i));
//                        }
//                        Collections.sort(driverSystemCargoList);
//                        for (int i = listResult.getData().size() - 1; i >= 0; i--) {
//                            driverSystemCargoSortList.add(driverSystemCargoMap.get(driverSystemCargoList.get(i)));
//                        }
//                    }

                    List<CargoDTO> driverSystemCargoSortList = new ArrayList();
                    if (listResult.getData() != null && listResult.getData().size() != 0){
                        for (CargoDTO cargoDTO : listResult.getData()) {
                            driverSystemCargoSortList.add(cargoDTO);
                        }
//                        driverSystemCargoSortList.sort(Comparator.comparing(CargoDTO::getCargoPrice));
                        driverSystemCargoSortList.sort((a, b) -> b.getCargoPrice().compareTo(a.getCargoPrice()));
                    }
                    return driverSystemCargoSortList;
                }
            };
            Future<List<CargoDTO>> driverSystemCargoSortListFuture = executor.submit(driverSystemCargoSortListCall);



            // 结束时间
            long end = System.currentTimeMillis();
            long all = end - start;
            System.out.println(all);


            // 价格排序后的不可抢货源
            twoCargoList.add(driverCanNotGrabCargoSortListFuture.get());
            // 价格排序后的可抢货源g
            twoCargoList.add(driverCanGrabCargoSortListFuture.get());
            // 价格排序后的系统货源
            twoCargoList.add(driverSystemCargoSortListFuture.get());
            return Result.success(twoCargoList);


        } else if (cargoSortNum != null && cargoSortNum == 2) { // cargoSortNum = 2 时进行距离排序
//            long start = System.currentTimeMillis();
            // 可抢按距离排序
//            Map<Double, CargoDTO> driverCanGrabDisMap = new HashMap<>();
//            List cargoDisList = new ArrayList();
//            if (driverCanGrabCargoList.size() != 0) {
//                for (int i = 0; i < driverCanGrabCargoList.size(); i++) {
//                    cargoDisList.add(driverCanGrabCargoList.get(i).getCargoEmptyDistance());
//                    driverCanGrabDisMap.put(driverCanGrabCargoList.get(i).getCargoEmptyDistance(), driverCanGrabCargoList.get(i));
//                }
//                Collections.sort(cargoDisList);
//            }
//            List driverCanGrabDisSortList = new ArrayList();
//            for (int i = 0; i < driverCanGrabCargoList.size(); i++) {
//                driverCanGrabDisSortList.add(driverCanGrabDisMap.get(cargoDisList.get(i)));
//            }

            List<CargoDTO> driverCanGrabDisSortList = new ArrayList(driverCanGrabCargoList);
            driverCanGrabDisSortList.sort(Comparator.comparing(CargoDTO::getCargoEmptyDistance));



//            Map<Double, CargoDTO> driverCanNotGrabDisMap = new HashMap<>();
//            List cargoNotDisList = new ArrayList();
//            if (driverCanNotGrabCargoList.size() != 0) {
//                for (int i = 0; i < driverCanNotGrabCargoList.size(); i++) {
//                    cargoNotDisList.add(driverCanNotGrabCargoList.get(i).getCargoEmptyDistance());
//                    driverCanNotGrabDisMap.put(driverCanNotGrabCargoList.get(i).getCargoEmptyDistance(), driverCanNotGrabCargoList.get(i));
//                }
//                Collections.sort(cargoNotDisList);
//            }
//            List driverCanNotGrabDisSortList = new ArrayList();
//            for (int i = 0; i < driverCanNotGrabCargoList.size(); i++) {
//                driverCanNotGrabDisSortList.add(driverCanNotGrabDisMap.get(cargoNotDisList.get(i)));
//            }
            List<CargoDTO> driverCanNotGrabDisSortList = new ArrayList(driverCanNotGrabCargoList);
            driverCanNotGrabDisSortList.sort(Comparator.comparing(CargoDTO::getCargoEmptyDistance));


//            Map<Double, CargoDTO> driverSystemDisMap = new HashMap<>();
//            List cargoSystemDisList = new ArrayList();
//            List driverSystemDisSortList = new ArrayList();
//            if (listResult.getData() != null && listResult.getData().size() != 0) {
//                for (int i = 0; i < listResult.getData().size(); i++) {
//                    cargoSystemDisList.add(listResult.getData().get(i).getCargoEmptyDistance());
//                    driverSystemDisMap.put(listResult.getData().get(i).getCargoEmptyDistance(), listResult.getData().get(i));
//                }
//                Collections.sort(cargoSystemDisList);
//                for (int i = 0; i < listResult.getData().size(); i++) {
//                    driverSystemDisSortList.add(driverSystemDisMap.get(cargoSystemDisList.get(i)));
//                }
//            }
            List<CargoDTO> driverSystemDisSortList = new ArrayList();
            if (listResult.getData() != null && listResult.getData().size() != 0){
                driverSystemDisSortList.addAll(listResult.getData());
                driverSystemDisSortList.sort(Comparator.comparing(CargoDTO::getCargoEmptyDistance));
            }

//            long end = System.currentTimeMillis();

//            long all = end - start;
//            System.out.println(all);


            // 距离排序后的不可抢货源
            twoCargoList.add(driverCanNotGrabDisSortList);
            // 距离排序后的可抢货源
            twoCargoList.add(driverCanGrabDisSortList);
            // 距离排序后的系统货源
            twoCargoList.add(driverSystemDisSortList);
            return Result.success(twoCargoList);


        }
        // 不排序
        twoCargoList.add(driverCanNotGrabCargoList);
        // 不排序
        twoCargoList.add(driverCanGrabCargoList);
        // 不排序
        twoCargoList.add(listResult.getData());

        System.out.println(twoCargoList.get(1));


        return Result.success(twoCargoList);

    }


    /**
     * 点击去抢单，跳转立即抢单页面  获取货源详情信息
     *
     * @param driverGrabDto
     * @return
     */
    @RequestMapping("/grabOrder")
    public Result grabOrder(DriverGrabDto driverGrabDto) {
        // 该接口没作用
        driverPersonalAllInformationService.grabOrder(driverGrabDto);

        com.ymm.system.api.dto.DriverGrabDTO driverGrabDTO = new DriverGrabDTO();
        BeanUtils.copyProperties(driverGrabDto, driverGrabDTO);


        // 获取货源详情
        com.ymm.system.api.utils.Result<CargoInfoDto> cargoInfoDtoResult = systemDisplayService.driverSearchCargoDetails(driverGrabDTO);
        CargoInfoDto cargoInfoDto = cargoInfoDtoResult.getData();

        return Result.success(cargoInfoDto);
    }


    /**
     * 联系客服
     *
     * @return
     */
    @RequestMapping("/driverFeedBack")
    public Result driverFeedBack() {
        driverPersonalAllInformationService.driverFeedBack();
        return Result.success();
    }


    /**
     * 钱包提现
     * @param driverId
     * @param mount
     * @return
     */
    @RequestMapping("/subtractProfit")
    public Result subtractDriverProfit(BigInteger driverId, Double mount) {

        mount = mount * 100;
        // 提现
        Double finalMount = mount;
//        executor.execute(() -> driverPersonalAllInformationService.subtractDriverProfit(driverId, finalMount));
        Result result = driverPersonalAllInformationService.subtractDriverProfit(driverId, mount);
        if (result.getCode() == 201) {
            return Result.fail("账户余额不足，不能提现");
        }
        // 更新流水到账单
        String description = "普通提现";
        driverPersonalAllInformationService.drbillNormalSubtractPrice(driverId, -mount, 2, description);

        // 返回更新后的账户钱包
        return Result.success(result.getData());

    }


    /**
     * 钱包充值且更新流水到司机流水账单，水流类型：1，普通充值
     *
     * @param driverId
     * @param mount
     * @return
     */
    @RequestMapping("/addProfit")
    public Result driverAddProfit(BigInteger driverId, Double mount) {

        // 获取当前钱包余额
        Double driverProfit = driverPersonalAllInformationService.getDriverProfitById(driverId).getData();
        mount *= 100;
        // 增加余额
        driverProfit += mount;
        // 更新到数据库
        driverPersonalAllInformationService.addDriverProfit(driverId, driverProfit);


        // 更新到流水账单
        String drbillDescription = "钱包充值";
        driverPersonalAllInformationService.drbillNormalAddPrice(driverId, mount, 1, drbillDescription);


        return Result.success(driverProfit);
    }


    /**
     * 进入钱包
     *
     * @param driverId
     * @return
     */
    @RequestMapping("/wallet")
    public Result driverWallet(BigInteger driverId) {

        BigDecimal driverWallet = driverPersonalAllInformationService.driverWallet(driverId);
        return Result.success(driverWallet);
    }


    /**
     * 司机加入会员 前端传数字，月会员传 1； 季会员传 3； 年会员传 12
     * 司机账户扣取会员费并更新到账单流水
     *
     * @param driverId
     * @param vipType    会员类型：1：月会员； 3：季会员； 12：年会员
     * @param ：30，90，360 RMB
     * @return
     */
    @RequestMapping("/joinVIP")
    public Result joinVIP(BigInteger driverId, Integer vipType) {

        // 司机钱包账户会员费
        Double vipPrice = 30.0 * vipType * 100;
        Result result = driverPersonalAllInformationService.subtractDriverProfit(driverId, vipPrice);
        if (result.getCode() == 201) {
            return Result.fail("账户余额不足，开通会员失败！");
        }


        // 将司机的状态变成会员状态，不管之前是不是，现在都是
        driverPersonalAllInformationService.driverJoinVIP(driverId);

        // 获取数据库中会员的到期时间
        Date driverVipTime = driverPersonalAllInformationService.queryNowVipTime(driverId).getDriverVipTime();
        String vipNowTime = null;

        try {
            if (driverVipTime != null) {
                // 如果当前就是会员，获取会员到期时间
                vipNowTime = DateUtils.parseDate2String(driverVipTime);
            } else {
                // 如果当前不是会员，那就用当前时间
                Date date = new Date();
                vipNowTime = DateUtils.parseDate2String(date);
            }


            //加的天数(月会员：vipTime=1；季会员：vipTime=3；年会员：vipTime=12)
            int num = 30 * vipType;
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date temp = format.parse(vipNowTime);
            Calendar ca = Calendar.getInstance();
            ca.setTime(temp);
            ca.add(Calendar.DATE, num);
            temp = ca.getTime();

            // 最新会员到期时间
            String vipNewTime = format.format(temp);

            // 将最新会员到期时间更新到数据库
            driverPersonalAllInformationService.driverVipTime(driverId, DateUtils.parseString2Date(vipNewTime, "yyyy-MM-dd"));




            // 更新到流水账单
            String description = "续费会员";
            driverPersonalAllInformationService.drbillNormalSubtractPrice(driverId, -vipPrice, 3, description);


            return Result.success(vipNewTime);
        } catch (Exception e) {
            e.printStackTrace();
        }


        return Result.fail("会员开通失败！");

    }


    /**
     * 修改个人信息
     *
     * @param driverId
     * @param driverPhone
     * @param driverCarType
     * @param driverCarNum
     * @return
     */
    @RequestMapping("/submitDriverInfo")
    public Result submitInformation(BigInteger driverId, String driverPhone, Integer driverCarType, String driverCarNum) {

        log.info("driverId:{}", driverId);
        log.info("driverCarType:{}", driverCarType);
        log.info("driverCarNum:{}", driverCarNum);
        log.info("driverPhone:{}", driverPhone);

        // 修改的手机号已存在
        String driverSearchPhone = driverPersonalAllInformationService.queryDriverByPhone(driverPhone);
        if (driverPhone.equals(driverSearchPhone)) return Result.fail("fuck the same phone!");

        driverPersonalAllInformationService.submitInformation(driverId, driverPhone, driverCarType, driverCarNum);
        Result<DriverEntity> driverEntityResult = driverPersonalAllInformationService.driverSearchInfo(driverId);
        return Result.success(driverEntityResult);

    }


    /**
     * 点击编辑进入个人信息，显示司机详细信息数据
     *
     * @param driverId
     * @return
     */
    @RequestMapping("/editorPersonInformation")
    public Result driverEditorPersonInformation(BigInteger driverId) {

        log.info("driverId:{}", driverId);

        DriverDto driverDto = driverPersonalAllInformationService.driverEditorPersonInformation(driverId);
        System.out.println(driverDto.getDriverSex());
        System.out.println(driverDto.getDriverCarNum());
        System.out.println(driverDto.getDriverCarType());
        System.out.println(driverDto.getDriverIdNum());
        System.out.println(driverDto.getDriverName());
        System.out.println(driverDto.getDriverPhone());

        return Result.success(driverDto);
    }


    /**
     * 进入个人中心功能
     *
     * @return
     */
    @RequestMapping("/personalCenter")
    public Result driverPersonalCenter() {

        driverPersonalAllInformationService.driverPersonalCenter();
        return Result.success();
    }


    /**
     * 司机认证，认证即通过
     *
     * @param driverIdNum
     * @param driverName
     * @param driverCarType
     * @param driverCarNum
     * @return
     */
    @RequestMapping("/authentication")
    public Result driverAuthentication(String driverPhone, String driverIdNum, String driverName, Integer driverCarType, String driverCarNum, Integer driverSex) {


        log.info("driverIdNum:{}", driverIdNum);
        log.info("driverName:{}", driverName);
        log.info("driverCarType:{}", driverCarType);
        log.info("driverCarNum:{}", driverCarNum);
        log.info("driverPhone:{}", driverPhone);
        log.info("driverSex:{}", driverSex);
        driverPersonalAllInformationService.driverAuthentication(driverPhone, driverIdNum, driverName, driverCarType, driverCarNum, driverSex);
        return Result.success();
    }


    /**
     * 司机身份认证
     * 使用异步方式实现批量认证
     *
     * @param driverPhone
     * @param driverIdNum
     * @param driverName
     * @param driverSex
     * @return
     */
    @RequestMapping("/driverInfoAuthentication")
    public Result driverInfoAuthentication(String driverPhone, String driverIdNum, String driverName, Integer driverSex) {

        executor.execute(() -> driverPersonalAllInformationService.driverInfoAuthentication(driverPhone, driverIdNum, driverName, driverSex));
        return Result.success("身份认证成功！");
    }

    /**
     * 车辆信息认证
     *
     * @param driverPhone
     * @param driverCarType
     * @param driverCarNum
     * @return
     */
    @RequestMapping("/carInfoAuthentication")
    public Result carInfoAuthentication(String driverPhone, Integer driverCarType, String driverCarNum) {

        executor.execute(() -> driverPersonalAllInformationService.carInfoAuthentication(driverPhone, driverCarType, driverCarNum));
        return Result.success("车辆信息认证成功！");
    }


    /**
     * 忘记密码后修改密码
     *
     * @param driverPhone
     * @param driverPassword
     * @return
     */
    @RequestMapping("/forgetPwd")
    public Result driverForgetPassword(String driverPhone, String driverPassword) {
        log.info("driverPhone:{}", driverPhone);
        log.info("driverPassword:{}", driverPassword);

        // 手机号合法性校验
        if (!PhoneCheckUtils.isPhoneLegal(driverPhone)) {
            return Result.fail("手机号不合法，请重新输入！");
        }

        // 判断用户是否存在
        if (driverPersonalAllInformationService.queryDriverByPhone(driverPhone) == null) {
            return Result.fail("用户不存在");
        }

        // 密码要求
        if (driverPassword.length() < 6 || driverPassword.length() > 20) {
            return Result.fail("密码长度要求6-20个字符");
        }

        // 密码加密
        driverPassword = MD5Utils.md5(driverPassword);

        driverPersonalAllInformationService.driverChangePassword(driverPhone, driverPassword);
        return Result.success("密码修改成功！");
    }


    /**
     * 司机登录功能
     *
     * @param driverPhone
     * @param driverPassword
     * @return
     */
    @RequestMapping("/login")
    public Result driverLogin(String driverPhone, String driverPassword) {


        log.info("driverPhone:{}", driverPhone);
        log.info("driverPassword:{}", driverPassword);

        // 手机号合法性校验
        /*if (!PhoneCheckUtils.isPhoneLegal(driverPhone)) {
            return Result.fail("手机号不合法，请重新输入！");
        }*/

        // 密码加密
        driverPassword = MD5Utils.md5(driverPassword);

        // 判断用户是否存在
        if (driverPersonalAllInformationService.queryDriverByPhone(driverPhone) == null) {
            return Result.fail("用户不存在");
        }

        // 密码校验
        String password = driverPersonalAllInformationService.driverLoginService(driverPhone).getDriverPwd();
        if (password.equals(driverPassword)) {
            // 将用户信息返回给前端
            DriverEntity driverEntity = driverPersonalAllInformationService.driverLoginService(driverPhone);
            return Result.success(driverEntity);
        }

        return Result.fail("密码不正确！");

    }


    /**
     * 司机注册功能
     *
     * @param driverPhone
     * @param driverPassword
     * @return
     */
    @RequestMapping("/register")
    public Result driverRegister(String driverPhone, String driverPassword) {


        log.info("driverPhone:{}", driverPhone);
        log.info("driverPassword:{}", driverPassword);


        // 1. 手机号合法性校验
        if (!PhoneCheckUtils.isPhoneLegal(driverPhone)) {
            return Result.fail("手机号不合法，请重新输入！");
        }

        // 2. 密码的要求:8-20
        if (driverPassword.length() < 6 || driverPassword.length() > 20) {
            return Result.fail("密码长度要求6-20个字符");
        }


        /**
         * 数据库中有此司机用户，不能重复注册
         */
        if (driverPersonalAllInformationService.queryDriverByPhone(driverPhone) != null) {
            return Result.fail("用户已存在，不能重复注册");
        }

        // 3. 密码加密
        driverPassword = MD5Utils.md5(driverPassword);

        driverPersonalAllInformationService.driverRegisterService(driverPhone, driverPassword);
        return Result.success("注册成功！");


    }


    /**
     * 造数平台
     *
     * @param driverPhone
     * @param driverPassword
     * @return
     */
    @RequestMapping("/test")
    public Result test(String driverPhone, String driverPassword) {


        driverPassword = "1";
        driverPassword = MD5Utils.md5(driverPassword);

        for (int i = 0; i < 100; i++) {
            String tem = "1" + i;
            System.out.println(tem);
            driverPhone = tem;
            driverPersonalAllInformationService.test(driverPhone, driverPassword);
        }
        return Result.success();
    }


    /**
     * 司机造数平台专用
     */
    @Reference
    private CreateRandomNumService createRandomNumService;


    /**
     * 司机造数平台
     * @param driverName
     * @param driverType
     * @param driverPhone
     * @param driverPwd
     * @param driverCarType
     * @param driverCarNum
     * @param driverIdNum
     * @param driverProfit
     * @param driverSex
     * @param driverBankCard
     * @param driverCredit
     * @return
     */
    @RequestMapping("/createNum")
    public Result createRandomRum(String driverName, Integer driverType, String driverPhone, String driverPwd,
                                  Integer driverCarType, String driverCarNum, String driverIdNum, Double driverProfit,
                                  Integer driverSex, String driverBankCard, Integer driverCredit) {


        for (int i = 1; i < 10; i++) {


            // 生成随机汉字
            char result = (char) (0x4e00 + (int) (Math.random() * (0x9fa5 - 0x4e00 + 1)));
            char result2 = (char) (0x4e00 + (int) (Math.random() * (0x9fa5 - 0x4e00 + 1)));
            char result3 = (char) (0x4e00 + (int) (Math.random() * (0x9fa5 - 0x4e00 + 1)));
            driverName = String.valueOf(result) + String.valueOf(result2) + String.valueOf(result3);
            System.out.println(driverName);


            driverType = 1;


            // 随机手机号
            Random random = new Random();
            StringBuilder sb = new StringBuilder();

            int op = random.nextInt(3);//随机运营商标志位
            sb.append(createMobile(op));
            if (i % 10 == 0) {
                sb.append("\n");
            } else {
                sb.append("\t");
            }

            driverPhone = sb.toString();

            driverPwd = MD5Utils.md5("123456");

            driverCarType = 8;

            driverCarNum = getCarNum();

            driverIdNum = getRandomID();

            driverProfit = 5000.00;

            driverSex = 1;

            driverBankCard = getRandomID();

            driverCredit = 500;


            createRandomNumService.createRandomNum(driverName, driverType, driverPhone, driverPwd, driverCarType, driverCarNum, driverIdNum, driverProfit, driverSex, driverBankCard, driverCredit);
        }
        return Result.success();
    }


    /**
     * 随即手机号工具
     */
    //中国移动
    public static final String[] CHINA_MOBILE = {
            "134", "135", "136", "137", "138", "139", "150", "151", "152", "157", "158", "159",
            "182", "183", "184", "187", "188", "178", "147", "172", "198"
    };
    //中国联通
    public static final String[] CHINA_UNICOM = {
            "130", "131", "132", "145", "155", "156", "166", "171", "175", "176", "185", "186", "166"
    };
    //中国电信
    public static final String[] CHINA_TELECOME = {
            "133", "149", "153", "173", "177", "180", "181", "189", "199"
    };

    /**
     * 生成手机号
     *
     * @param op 0 移动 1 联通 2 电信
     */
    public static String createMobile(int op) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        String mobile01;//手机号前三位
        int temp;
        switch (op) {
            case 0:
                mobile01 = CHINA_MOBILE[random.nextInt(CHINA_MOBILE.length)];
                break;
            case 1:
                mobile01 = CHINA_UNICOM[random.nextInt(CHINA_UNICOM.length)];
                break;
            case 2:
                mobile01 = CHINA_TELECOME[random.nextInt(CHINA_TELECOME.length)];
                break;
            default:
                mobile01 = "op标志位有误！";
                break;
        }
        if (mobile01.length() > 3) {
            return mobile01;
        }
        sb.append(mobile01);
        //生成手机号后8位
        for (int i = 0; i < 8; i++) {
            temp = random.nextInt(10);
            sb.append(temp);
        }
        return sb.toString();
    }





    /**
     * 生成随机车牌号工具
     */
    /**
     * 中国各个地区的数组
     */
    private static final String[] CAR_AREA_ARRAY = {"京", "津", "沪", "渝", "冀", "豫", "云", "辽", "黑",
            "湘", "皖", "鲁", "新", "苏", "浙", "赣", "鄂", "桂", "甘", "晋", "蒙", "陕", "吉", "闽", "贵", "粤", "青", "藏",
            "川", "宁", "琼"};

    /**
     * 城市代码，不能有字母 I 和 O
     */
    private static final String[] CAR_LETTER_ARRAY = {"A", "B", "C", "D", "E", "F", "G", "H", "J", "K",
            "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V"};

    /**
     * 车牌号，不能有字母 I 和 O
     */
    private static final String[] CAR_CHAR_ARRAY = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K",
            "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    /**
     * 车牌编号长度
     */
    private static final int CAR_NUM_LENGTH = 5;

    public static String getCarNum() {
        // 随机获取地区
        String area = CAR_AREA_ARRAY[(int) (Math.random() * CAR_AREA_ARRAY.length)];

        // 随机生成城市编号
        String cityCode = CAR_LETTER_ARRAY[(int) (Math.random() * CAR_LETTER_ARRAY.length)];

        // 循环5次，生成车牌号
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < CAR_NUM_LENGTH; i++) {
            sb.append(CAR_CHAR_ARRAY[(int) (Math.random() * CAR_CHAR_ARRAY.length)]);
        }

        // 拼接
        return area + cityCode + sb;
    }





    /**
     * 生成随机身份证号
     */

    public static String getRandomID() {
        String id = "";
        // 随机生成省、自治区、直辖市代码 1-2
        String provinces[] = {"11", "12", "13", "14", "15", "21", "22", "23",
                "31", "32", "33", "34", "35", "36", "37", "41", "42", "43",
                "44", "45", "46", "50", "51", "52", "53", "54", "61", "62",
                "63", "64", "65", "71", "81", "82"};
        String province = provinces[new Random().nextInt(provinces.length - 1)];
        // 随机生成地级市、盟、自治州代码 3-4
        String citys[] = {"01", "02", "03", "04", "05", "06", "07", "08",
                "09", "10", "21", "22", "23", "24", "25", "26", "27", "28"};
        String city = citys[new Random().nextInt(citys.length - 1)];
        // 随机生成县、县级市、区代码 5-6
        String countys[] = {"01", "02", "03", "04", "05", "06", "07", "08",
                "09", "10", "21", "22", "23", "24", "25", "26", "27", "28",
                "29", "30", "31", "32", "33", "34", "35", "36", "37", "38"};
        String county = countys[new Random().nextInt(countys.length - 1)];
        // 随机生成出生年月 7-14
        SimpleDateFormat dft = new SimpleDateFormat("yyyyMMdd");
        Date beginDate = new Date();
        Calendar date = Calendar.getInstance();
        date.setTime(beginDate);
        date.set(Calendar.DATE,
                date.get(Calendar.DATE) - new Random().nextInt(365 * 100));
        String birth = dft.format(date.getTime());
        // 随机生成顺序号 15-17
        String no = new Random().nextInt(999) + "";
        // 随机生成校验码 18
        String checks[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
                "X"};
        String check = checks[new Random().nextInt(checks.length - 1)];
        // 拼接身份证号码
        id = province + city + county + birth + no + check;
        return id;
    }

}


